import { getCurrentGoal, addGoal, updateGoal } from '@/api/goals'

export default {
  namespaced: true,
  
  state: {
    currentGoal: null,
    goalHistory: []
  },
  
  mutations: {
    SET_CURRENT_GOAL(state, goal) {
      state.currentGoal = goal
    },
    SET_GOAL_HISTORY(state, goals) {
      state.goalHistory = goals
    },
    UPDATE_GOAL(state, updatedGoal) {
      if (state.currentGoal?.goalId === updatedGoal.goalId) {
        state.currentGoal = updatedGoal
      }
      state.goalHistory = state.goalHistory.map(goal => 
        goal.goalId === updatedGoal.goalId ? updatedGoal : goal
      )
    },
    ADD_GOAL(state, goal) {
      if (goal.goalId) {
        state.goalHistory.unshift(goal)
      }
    }
  },
  
  actions: {
    // 获取当前目标
    async fetchCurrentGoal({ commit }, userId) {
      try {
        const response = await getCurrentGoal(userId)
        if (response?.success) {
          commit('SET_CURRENT_GOAL', response.data)
          return response.data
        }
        return null
      } catch (error) {
        console.error('获取当前目标失败:', error)
        throw error
      }
    },
    
    // 添加新目标
    async addNewGoal({ commit }, { userId, goalData }) {
      try {
        const response = await addGoal(userId, goalData)
        if (response?.success) {
          commit('ADD_GOAL', response.data)
          return response.data
        }
        throw new Error(response?.message || '添加目标失败')
      } catch (error) {
        console.error('添加目标失败:', error)
        throw error
      }
    },
    
    // 更新目标
    async updateGoal({ commit }, { userId, goalId, goalData }) {
      try {
        const response = await updateGoal(userId, goalId, goalData)
        if (response?.success) {
          commit('UPDATE_GOAL', response.data)
          return response.data
        }
        throw new Error(response?.message || '更新目标失败')
      } catch (error) {
        console.error('更新目标失败:', error)
        throw error
      }
    }
  },
  
  getters: {
    currentGoal: state => state.currentGoal,
    goalHistory: state => state.goalHistory
  }
} 